package com.mrd.gtimpframe.action;

import com.mrd.base.Jqgrid;
import com.mrd.framework.config.web.json.Result;
import com.mrd.gtimpframe.entity.Dictionary;
import com.mrd.gtimpframe.entity.DictionaryGroup;
import com.mrd.gtimpframe.repository.DictionaryGroupMapper;
import com.mrd.gtimpframe.service.DictionaryService;
import com.mrd.util.LoginUtil;
import com.mrd.util.StringUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

/**
 * Created by dark on 17/7/20.
 */
@Controller
@RequestMapping("/api/dictionary")
public class DictionaryAction {

    @Resource
    private DictionaryGroupMapper dictionaryGroupMapper;

    @Resource
    private DictionaryService dictionaryService;

    /**
     * 基础数据管理列表页面
     */
    @RequestMapping("/mainPage")
    public String mainPage(String groupCode, String groupId, Model model) {
        model.addAttribute("groupCode", groupCode);
        model.addAttribute("groupId", groupId);
        return "/gtimpframe/dictionary/main";
    }

    /**
     * 基础数据管理详细页面
     */
    @RequestMapping("/detailPage")
    public String detailPage(String id, String groupId, String groupCode, Model model) {
        if (StringUtils.isNotEmpty(groupCode) && StringUtils.isEmpty(groupId)) {
            DictionaryGroup dictionaryGroup = dictionaryGroupMapper.selectByCode(groupCode);
            if (dictionaryGroup != null) {
                groupId = dictionaryGroup.getId();
            }
        }
        model.addAttribute("groupId", groupId);
        model.addAttribute("id", id);
        return "/gtimpframe/dictionary/detail";
    }

    @RequestMapping("/findByGroupId")
    @ResponseBody
    public Map<String, Object> findPageList(Jqgrid jqgrid, String id) {
        Page<Map<String, Object>> listPageData = findPageList(jqgrid, null, id);
        Map<String, Object> subGridMap = new HashMap<>();
        subGridMap.put("page", jqgrid.getPage().getPageNumber() + 1);
        List<Map<String, Object>> rows = new ArrayList<>();
        for (Map<String, Object> objectMap : listPageData.getContent()) {
            Map<String, Object> rowMap = new HashMap<>();
            rowMap.put("id", objectMap.get("ID"));
            List<Object> cell = new ArrayList<>();
            cell.add(objectMap.get("DICTIONARY_CODE"));
            cell.add(objectMap.get("DICTIONARY_NAME"));
            cell.add(objectMap.get("DESCRIPT"));
            cell.add(objectMap.get("CREATOR"));
            cell.add(objectMap.get("CREATE_TIME"));
            cell.add(objectMap.get("MODIFIER"));
            cell.add(objectMap.get("MODIFY_TIME"));
            rowMap.put("cell", cell);
            rows.add(rowMap);
        }
        subGridMap.put("total", listPageData.getTotalElements());
        subGridMap.put("records", listPageData.getNumberOfElements());
        subGridMap.put("rows", rows);
        return subGridMap;
    }

    @RequestMapping("/findPageList")
    @ResponseBody
    public Page<Map<String, Object>> findPageList(Jqgrid jqgrid, String groupCode, String groupId) {
        Pageable page = jqgrid.getPage();
        // 分页
        jqgrid.pageWithMybatis();

        // 组装查询条件
        Map<String, Object> parameterMap = new HashMap<>();
        if (StringUtils.isNotEmpty(groupCode)) {
            parameterMap.put("group_code", groupCode);
        }
        if (StringUtils.isNotEmpty(groupId)) {
            parameterMap.put("group_id", groupId);
        }
        parameterMap.putAll(jqgrid.getFilterMap());

        // 排序
        jqgrid.sortWithMybatis();

        return dictionaryService.listPageData(page, parameterMap);
    }

    /**
     * 根据主键ID获取字典
     *
     * @param id 主键ID
     */
    @RequestMapping("/findById")
    @ResponseBody
    public Dictionary findById(String id) {
        if (StringUtils.isNotEmpty(id)) {
            Dictionary dictionary = dictionaryService.selectByPrimaryKey(id);
            return dictionary;
        }
        return null;
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Result saveOrUpdate(Dictionary dictionary, String groupId) {
        if (StringUtils.isEmpty(groupId)) {
            return Result.newFailInstance("保存失败！");
        }
        if (StringUtils.isEmpty(dictionary.getDictionaryName()) || StringUtils.isEmpty(dictionary.getStatus())) {
            return Result.newFailInstance("字典名称或字典状态为空！");
        }
        int result;
        if (dictionary != null && StringUtils.isNotEmpty(dictionary.getId())) {
            dictionary.setModifier(LoginUtil.getLoginAccount());
            dictionary.setModifyTime(new Date());
            dictionary.setGroupId(groupId);
            result = dictionaryService.updateByPrimaryKeySelective(dictionary);
        } else {
            dictionary.setId(com.mrd.util.StringUtils.getUUID());
            dictionary.setCreator(LoginUtil.getLoginAccount());
            dictionary.setCreateTime(new Date());
            result = dictionaryService.insert(dictionary);
        }
        return result > 0 ? Result.newSuccessInstance("保存成功！") : Result.newFailInstance("保存失败！");
    }

    /**
     * 逻辑删除
     *
     * @param id 主键id
     */
    @RequestMapping("/deleteDictionary")
    @ResponseBody
    public Result deleteDictionary(String id) {
        if (StringUtils.isNotEmpty(id)) {
            int result = dictionaryService.updateDeleteStateByPrimaryKey(id);
            if (result > 0) {
                return Result.newSuccessInstance("删除成功！");
            }
        }
        return Result.newFailInstance("删除失败！");
    }

    /**
     * 根据选择的字典组显示下面的字典信息
     *
     * @param dtGroupId 字典组ID
     */
    @RequestMapping("/search")
    @ResponseBody
    public Map<String, Object> search(String dtGroupId, String dtGroupCode) {
        Map<String, Object> result = new HashedMap();
        if (StringUtils.isEmpty(dtGroupId) && StringUtils.isEmpty(dtGroupCode)) {
            result.put("error_code", "1");
            return result;
        }
        List<Dictionary> dictionaryList = null;
        if (StringUtils.isNotEmpty(dtGroupCode)) {
            dictionaryList = dictionaryService.selectWithDictionaryByCodesIn(dtGroupCode);
        } else if (StringUtils.isNotEmpty(dtGroupId)) {
            dictionaryList = dictionaryService.selectWithDictionaryByPrimaryKey(dtGroupId);
        }
        List<Map<String, Object>> contentList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(dictionaryList)) {
            if (CollectionUtils.isNotEmpty(dictionaryList)) {
                for (Dictionary dictionary : dictionaryList) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("dtId", dictionary.getId());
                    map.put("dtKey", dictionary.getDictionaryCode());
                    map.put("dtValue", dictionary.getDictionaryName());
                    contentList.add(map);
                }
            }
        }
        result.put("error_code", "0");
        result.put("content", contentList);
        return result;
    }

    /**
     * 页面获取下拉框或多选项的数据
     *
     * @param codes 字典组编码
     */
    @RequestMapping("/getJsonByCodes")
    @ResponseBody
    public Map<String, Object> getJsonByCodes(String codes) {
        Map<String, Object> result = new HashMap();
        if (StringUtils.isEmpty(codes)) {
            result.put("error_code", "1");
            result.put("errMsg", "字典组编码为空！");
            return result;
        }
        List<String> codeList = new ArrayList<>();
        JSONObject jsonObject = JSONObject.fromObject(codes);
        JSONArray jsonArray = jsonObject.getJSONArray("codes");
        for (Object o : jsonArray) {
            codeList.add(o.toString());
        }
        List<Map<String, Object>> dictGroupList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(codeList)) {
            for (String dtgCode : codeList) {
                List<Dictionary> dictionaryList = dictionaryService.selectWithDictionaryByCodesIn(dtgCode);
                Map<String, Object> dictGroupMap = new HashMap();
                List<Map<String, Object>> dictList = new ArrayList<>();
                if (CollectionUtils.isNotEmpty(dictionaryList)) {
                    for (Dictionary dictionary : dictionaryList) {
                        Map<String, Object> dictMap = new HashMap<>();
                        dictMap.put("dtId", dictionary.getId());
                        dictMap.put("dtName", dictionary.getDictionaryName());
                        dictList.add(dictMap);
                    }
                }
                dictGroupMap.put(dtgCode, dictList);
                dictGroupList.add(dictGroupMap);
            }
        }
        result.put("error_code", "0");
        result.put("content", dictGroupList);
        return result;
    }

}
